package com.wego.controller;

import com.wego.common.bean.EntryBean;
import com.wego.common.bean.PageBean;
import com.wego.common.utils.QueryUtil;
import com.wego.constant.WeGoConst;
import com.wego.converter.PayMethodConverter;
import com.wego.converter.trans.AddressTrans;
import com.wego.converter.trans.OrderItemTrans;
import com.wego.converter.trans.OrderTrans;
import com.wego.entity.domain.Address;
import com.wego.entity.domain.Order;
import com.wego.entity.domain.OrderItem;
import com.wego.entity.domain.PayMethod;
import com.wego.entity.query.OrderQuery;
import com.wego.entity.vo.AddressVOFront;
import com.wego.entity.vo.manager.CartItemVO;
import com.wego.entity.vo.manager.CartVO;
import com.wego.entity.vo.manager.OrderItemVO;
import com.wego.entity.vo.manager.OrderVO;
import com.wego.entity.vo.manager.UserSessionVO;
import com.wego.service.AddressService;
import com.wego.service.CountryService;
import com.wego.service.OrderItemService;
import com.wego.service.OrderService;
import com.wego.service.PayMethodService;
import jakarta.servlet.http.HttpSession;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller("OrderControllerFront")
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private AddressService addressService;

    @Autowired
    private AddressTrans addressTrans;

    @Autowired
    private PayMethodService payMethodService;

    @Autowired
    private PayMethodConverter payMethodConverter;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderTrans orderTrans;

    @Autowired
    private OrderItemTrans orderItemTrans;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private CountryService countryService;


    /**
     * 打开订单页面
     * @param session
     * @param model
     * @return
     */
    @GetMapping("/openOrder")
    public String list(HttpSession session, Model model) {
        Object userObj = session.getAttribute(WeGoConst.SESSION_USER);
        //如果用户未登录，打开登录页面
        if (userObj == null) {
            return "redirect:user/openLogin";
        }
        UserSessionVO user = (UserSessionVO) userObj;

        //用户收件地址
        List<Address> addressList = addressService.selectList(Address.builder()
                .userId(user.getId())
                .state(1)
                .build());
        List<AddressVOFront> addressVOFrontList = addressTrans.getInstance2().tList2VList(addressList);
        model.addAttribute("addressList", addressVOFrontList);

        //支付方式列表
        List<PayMethod> payMethodList = payMethodService.selectList(PayMethod.builder()
                .state(1)
                .build());
        List<EntryBean<String>> payMethodEntryList = payMethodConverter.payMethodList2EntryList(payMethodList);
        model.addAttribute("payMethodList", payMethodEntryList);

        return "order";
    }

    @GetMapping("/openOrderSuccess")
    public String openOrderSuccess() {
        return "order_success";
    }

    /**
     * 生成订单
     * @param goodsId 商品编号
     * @param amount 商品购买数量
     * @return
     */
    @GetMapping("/genOrder")
    public String genOrder(Long[] goodsId, Integer[] amount, Integer payMethodId, Long addressId, HttpSession session) {
        if (goodsId.length != amount.length) {
            //用户提交的参数不正确
        }
        //Session中保存的登录用户的信息
        UserSessionVO userSessionVO = (UserSessionVO) session.getAttribute(WeGoConst.SESSION_USER);
        if (userSessionVO == null) {
            //用户未登录，打开登录页面
            return "/user/openLogin";
        }

        //生成订单
        orderService.genOrder(goodsId, amount, payMethodId, addressId, userSessionVO.getId());

        //删除Session购物车中已经购买的商品
        CartVO cart = (CartVO) session.getAttribute(WeGoConst.CART);
        if (cart != null) {
            List<CartItemVO> cartItemVOs = cart.getCartItemVOs();
            for (Long id : goodsId) {
                cartItemVOs.remove(CartItemVO.builder()
                        //GoodsId是区分CartItemVO的唯一标识
                        .goodsId(id)
                        .build());
            }
        }

        //用来防止表单重复提交
        return "redirect:openOrderSuccess";
    }

    /**
     * 查询当前登录用户的所有订单信息
     * @param orderQuery
     * @param model
     * @param session
     * @return
     */
    @GetMapping("/selectOrderByCurrentUser")
    public String selectOrderByCurrentUser(OrderQuery orderQuery, Model model,HttpSession session) {
        //构造动态查询条件
        //String keywords = orderQuery.getKeywords();
        //if (keywords != null) {
        //
        //}

        UserSessionVO userSessionVO = (UserSessionVO) session.getAttribute(WeGoConst.SESSION_USER);
        if (userSessionVO == null) {
            //用户未登录，打开登录页面
            return "/user/openLogin";
        }
        
        //获取订单信息
        orderQuery.setUserIds(List.of(userSessionVO.getId()));
        final PageBean<Order> orderPageBean = orderService.selectPage(orderQuery);

        PageBean<OrderVO> pageBean = orderTrans.getInstance().tPageBean2VPageBean(orderPageBean);

        //分页时携带上查询条件
        String params = QueryUtil.genQueryCondition(orderQuery);
        pageBean.setUrl("manager/order/list?" + params);
        model.addAttribute("pageBean", pageBean);

        return "order_list";
    }

    /**
     * 订单详情
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/details")
    public String details(Long id, Model model) {
        Order order = orderService.selectByPrimaryKey(id);
        //转换
        final OrderVO orderVO = orderTrans.getInstance().tObj2VObj(order);
        model.addAttribute("order", orderVO);

        List<OrderItem> orderItemList = orderItemService.selectOrderItemByOrderId(id);
        //转换
        final List<OrderItemVO> orderItemVOList = orderItemTrans.getInstance().tList2VList(orderItemList);
        model.addAttribute("orderItemList", orderItemVOList);

        //获取省份-城市-县区列表
        final Address address = addressService.selectByPrimaryKey(order.getAddressId());
        final List<EntryBean<String>> pccList = countryService.selectProvinceCityCountryByCountryId(address.getCountryId());
        model.addAttribute("pccList", pccList);

        return "order_details";
    }
}